package com.jinlejia.erp.ui.home;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.jinlejia.erp.R;
import com.jinlejia.erp.adapter.AppVisitDetailsAdapter;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.databinding.ActivityVisitDetailsBinding;
import com.jinlejia.erp.ui.common.CallUpDialog;
import com.jinlejia.erp.ui.common.DeleteDialog;
import com.jinlejia.erp.ui.common.FinishDialog;
import com.jinlejia.erp.ui.common.ShareDialog;
import com.jinlejia.erp.ui.customer.EnteringVisitActivity1;
import com.jinlejia.erp.ui.house.HouseDetailActivity;
import com.jinlejia.erp.utils.CallUtils;
import com.jinlejia.erp.utils.DataFilter;
import com.jinlejia.erp.utils.DateUtil;
import com.weight.CustomToast;
import com.zhy.http.okhttp.OkHttpUtils;

import org.simple.eventbus.EventBus;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Map;

import okhttp3.Call;
import okhttp3.MediaType;

/**
 * 约看详情（Activity）
 */

public class AppVisitDetailsActivity extends AppCompatActivity {


    private String phoneNO;
    private FinishDialog finishDialog;
    private DeleteDialog deleteDialog;

    private AppVisitDetailsAdapter adapter;

    private ArrayList<Map<String, Object>> dataList = new ArrayList<>();
    private Map<String, Object> map;
    private CallUpDialog dialog;
    private JSONObject jsonObject = new JSONObject();
    private String customerName, type, firsttime, lasttime, place, pointx, pointy, endtime;
    private int number;

    private String shareSubject = "";
    private String shareContent = "";
    private String shareUrl = "";
    private String smsBody="";
    private String smsTo="";
    public String url_icon = ApiConfig.HEADER_URL()+"T1BoDVBy_T1RXrhCrK.jpg";

    private ActivityVisitDetailsBinding binding;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_visit_details);
        binding.setEvent(this);
        initView();
        initEvent();
    }

    @Override
    protected void onStart() {
        super.onStart();
        getData();
    }

    /**
     * 初始化视图
     */
    private void initView() {

        finishDialog = new FinishDialog(this);
        deleteDialog = new DeleteDialog(this);


        binding.visitDetailsRecycler.setHasFixedSize(true);
        binding.visitDetailsRecycler.setLayoutManager(new LinearLayoutManager(this));


        adapter = new AppVisitDetailsAdapter(dataList);
        binding.visitDetailsRecycler.setAdapter(adapter);
    }

    /**
     * 初始化事件
     */
    private void initEvent() {
        finishDialog.setConfirmListener(this::FinishData);
        deleteDialog.setConfirmListener(this::DeleteData);

        adapter.setOnItemClickListener((view, o) -> {
            Intent intent = new Intent(AppVisitDetailsActivity.this, HouseDetailActivity.class);
            intent.putExtra("code", ((Map<String, Object>) o).get("rsCode").toString());
            if (((Map<String, Object>) o).get("type").toString().equals("1")) {
                intent.putExtra("type", "shs");
            } else {
                intent.putExtra("type", "rent");
            }
            startActivity(intent);
        });
    }


    public void onClick(View view) {
        Intent intent = null;
        switch (view.getId()) {
            case R.id.back_btn:
                finish();
                break;
            case R.id.contact_client:   //联系客户
                dialog.show();
                break;
            case R.id.cancel_schedule:  //取消日程
                intent = new Intent(AppVisitDetailsActivity.this, CancelReasonActivity.class);
                intent.putExtra("appointmentCode", getIntent().getStringExtra("appointmentCode"));
                break;
            case R.id.visit_schedule:   //安排日程
                intent = new Intent(AppVisitDetailsActivity.this, VisitScheduleActivity.class);
                intent.putExtra("appointmentCode", getIntent().getStringExtra("appointmentCode"));
                intent.putExtra("customerName", customerName);
                intent.putExtra("firsttime", firsttime);
                intent.putExtra("lasttime", lasttime);
                intent.putExtra("endtime", endtime);
                intent.putExtra("number", number);
                intent.putExtra("place", place);
                intent.putExtra("pointx", pointx);
                intent.putExtra("pointy", pointy);
                intent.putExtra("type", type);
                intent.putExtra("sex", getIntent().getStringExtra("sex"));
                intent.putExtra("property", "Again");
                EventBus.getDefault().postSticky(adapter.getData(), "TAG_HOUSE_LIST");
                break;
            case R.id.delete_schedule:  //删除日程
                deleteDialog.show();
                break;
            case R.id.schedule_finish:  //完成带看
                finishDialog.show();
                break;
            case R.id.visit_details_send:
                //分享
                ShareDialog shareDialog = new ShareDialog(AppVisitDetailsActivity.this, shareSubject, shareContent,smsBody,smsTo, "", R.drawable.ic_share_jlj, shareUrl,url_icon);
                shareDialog.show();
                break;
            default:
                break;
        }
        if (intent != null) {
            startActivity(intent);
        }
    }

    /**
     * 获取数据
     */
    private void getData() {

        OkHttpUtils
                .get()
                .url(ApiConfig.APPOINTMENT_VISIT_DETAIL)
                .addParams("appointmentCode", getIntent().getStringExtra("appointmentCode"))
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (DataFilter.filter(AppVisitDetailsActivity.this, response, null)) {
                            SimpleDateFormat sdf1 = new SimpleDateFormat("HH:mm");
                            map = JSON.parseObject(response.get("data").toString(), new TypeReference<Map<String, Object>>() {
                            });
                            ArrayList<Map<String, Object>> list = JSON.parseObject(map.get("houseList").toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
                            });
                            type = map.get("type").toString();
                            for (int i = 0; i < list.size(); i++) {
                                list.get(i).put("type", type);
                            }
                            adapter.setData(list);

                            if (String.valueOf(map.get("isShow")).equals("0")) {
                                binding.bottomLayout.setVisibility(View.GONE);

                            } else if (String.valueOf(map.get("isShow")).equals("1")) {
                                if (map.containsKey("state")) {
                                    switch (map.get("state").toString()) {
                                        case "0":
                                            binding.detailsState.setText("未完成");
                                            binding.cancelSchedule.setVisibility(View.VISIBLE);
                                            binding.scheduleFinish.setVisibility(View.VISIBLE);
                                            binding.cancelReasonLayout.setVisibility(View.GONE);
                                            binding.reVisit.setText("安排日程");
                                            break;
                                        case "1":
                                            binding.detailsState.setText("已完成");
                                            binding.bottomLayout.setVisibility(View.GONE);
                                            break;
                                        case "2":
                                            binding.detailsState.setText("已取消");
                                            binding.cancelSchedule.setVisibility(View.GONE);
                                            binding.scheduleFinish.setVisibility(View.GONE);
                                            binding.cancelReasonLayout.setVisibility(View.VISIBLE);
                                            binding.reVisit.setText("重新安排日程");
                                            if (!TextUtils.isEmpty(map.get("cancleReason").toString()))
                                                binding.cancelReason.setText(map.get("cancleReason").toString());
                                            break;
                                        case "3":
                                            binding.detailsState.setText("已过期");
                                            binding.cancelSchedule.setVisibility(View.GONE);
                                            binding.reVisit.setText("重新安排日程");
                                            break;
                                    }
                                }
                            }

                            binding.agentName.setText(map.get("userName").toString());
                            if (String.valueOf(map.get("customerSex")).equals("0")) {
                                binding.name.setText(map.get("customerName").toString().concat(" 女士"));
                            } else if (String.valueOf(map.get("customerSex")).equals("1")) {
                                binding.name.setText(map.get("customerName").toString().concat(" 先生"));
                            }
                            customerName = map.get("customerName").toString();
                            binding.address.setText(map.get("address").toString());
                            place = map.get("address").toString();
                            pointx = map.get("longitude").toString();
                            pointy = map.get("latitude").toString();
                            /*
                            * TIME：2017-9-5
                            * BUGID: 2384
                            * MODIFIER: 王彤
                            * MODIFY: 修改内容  time 改为时间段
                            */
                            binding.time.setText(DateUtil.getTime(map.get("appointmentStartTime").toString(), "yyyy-MM-dd  HH:mm") + "-"
                            + sdf1.format(new Date(Long.valueOf(map.get("appointmentEndTime").toString()))));
                            firsttime = map.get("appointmentStartTime").toString();
                            lasttime = map.get("appointmentEndTime").toString();
                            endtime = map.get("appointmentEndTime").toString();
                            binding.houseAmount.setText("约看房源（" + map.get("countHouse").toString() + "）");
                            number = Integer.parseInt(map.get("countHouse").toString());

                            phoneNO = String.valueOf(map.get("customerTel"));
                            dialog = new CallUpDialog(AppVisitDetailsActivity.this, phoneNO);
                            dialog.setConfirmListener(() -> CallUtils.CallTel(AppVisitDetailsActivity.this,phoneNO));

                            shareSubject = DateUtil.getTime(firsttime,"MM月dd日").concat("看房计划");
                            if( list.size()>1 ){
                                shareContent = list.get(0).get("estate").toString().concat("等").concat(map.get("countHouse").toString()).concat("套房源");
                            }else{
                                shareContent = list.get(0).get("estate").toString();
                            }
                            shareUrl = map.get("shareLink").toString();
                            smsBody = binding.name.getText().toString().concat("您好！已经为您安排了").concat(shareSubject).concat(",详情请查看").concat(shareUrl).concat(".来自【进了家】");
                            smsTo = String.valueOf(map.get("customerTel"));
                        }
                    }
                });
    }

    /**
     * 完成带看
     */
    private void FinishData() {
        jsonObject.put("appointmentCode", getIntent().getStringExtra("appointmentCode"));
        OkHttpUtils
                .postString()
                .url(ApiConfig.FINISH_APPOINTMENT)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(jsonObject.toString())
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (DataFilter.filter(AppVisitDetailsActivity.this, response, null)) {
                            CustomToast.showToast(AppVisitDetailsActivity.this, "完成带看", 1500);
                            EventBus.getDefault().postSticky(map,"TAG_YUEKAN_INFO");
                            Intent intent = new Intent(AppVisitDetailsActivity.this, EnteringVisitActivity1.class);
                            startActivity(intent);
                        }
                    }
                });
    }

    /**
     * 删除日程
     */
    private void DeleteData() {
        jsonObject.put("appointmentCode", getIntent().getStringExtra("appointmentCode"));
        OkHttpUtils
                .postString()
                .url(ApiConfig.DELETE_APPOINTMENT)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(jsonObject.toString())
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (DataFilter.filter(AppVisitDetailsActivity.this, response, null)) {
                            CustomToast.showToast(AppVisitDetailsActivity.this, "删除成功", 2000);
                            setResult(RESULT_OK,new Intent());
                            finish();
                        }
                    }
                });
    }

}
